<template>
  <!--销售统计-->
  <div class="jeecg-basic-table jeecg-basic-table-form-container">
    <a-form @keyup.enter.native="searchQuery">
      <a-row :gutter="10" type="flex">
        <a-col flex="350px">
          <a-form-item label="放款日期" :label-col="{ style: { width: '70px' } }" :wrapper-col="{ style: { width: '250px' } }">
            <a-date-picker
              v-model:value="queryParam.beginDate"
              :disabled-date="disabledStartDate"
              valueFormat="YYYY-MM"
              placeholder=""
              style="width: 125px"
              picker="month"
            /> ~
            <a-date-picker
              v-model:value="queryParam.endDate"
              :disabled-date="disabledEndDate"
              valueFormat="YYYY-MM"
              placeholder=""
              style="width: 125px"
              picker="month"
            />
          </a-form-item>
        </a-col>

        <a-col flex="300px">
          <a-form-item label="资方产品" :label-col="{ style: { width: '66px' } }">
            <Cascader 
              v-model:value="cascader.ids" 
              :options="cascader.options" 
              :changeOnSelect="true"
              placeholder="请选择" 
              expandTrigger="hover"
              stringToNumber 
              @change="customerCascader" 
              :showSearch="false" 
            />
          </a-form-item>
        </a-col>

        <a-col flex="auto" style="float:right; width:150px; margin-right: 10px">
          <span style="float: right;overflow: hidden;" class="table-page-search-submitButtons">
            <a-button type="primary" @click="searchQuery" preIcon="ant-design:search">查询</a-button>
            <!--a-button type="default" @click="onExportXls" preIcon="ant-design:reload-outlined" style="margin-left: 8px">数据导出</a-button-->
          </span>
        </a-col>
      </a-row>
    </a-form>
  </div>

  <!-- table区域-begin -->
  <BasicTable @register="registerTable" :indentSize="8" :loading="loading"
    :onRowClick="handleClick" :onRowDbClick="handleDblclick" :rowClassName="rowClassName" :indexColumnProps="indexColumnProps"
  >

  </BasicTable>
  <!-- table区域-end -->

  <!-- 表单区域 -->
  <OrdersDetail @register="registerDetail" ></OrdersDetail>
</template>

<script lang="ts" setup name="report-orders">
import { nextTick, reactive, ref, onMounted } from "vue";
import { BasicTable, TableAction, ActionItem, BasicColumn } from "/@/components/Table";
import { useListPage } from "/@/hooks/system/useListPage";
import { useModal } from '/@/components/Modal';
import { defHttp } from "/@/utils/http/axios";
import { filterObj } from "/@/utils/common/compUtils";
import { businessCustomerExportUrl } from "/@/views/good/report/api";
import { useMethods } from "/@/hooks/system/useMethods";
import { Cascader } from 'ant-design-vue';
import { customerSelect } from '/@/views/good/product/Product.api';
import { render } from '/@/utils/common/renderUtils';

import OrdersDetail from './modules/OrdersDetail.vue';
import moment from 'dayjs'

//初始化 -------------------------------------------------------------
/**
 * 序号列配置
 */
 const indexColumnProps = {
  dataIndex: 'index',
  width: '15px',
};

//定义查询表单，查询条件
const queryParam = reactive<any>({
  beginDate : moment().subtract( 6, 'months').format('YYYY-MM'),
  endDate: moment().add( 0, 'months').endOf('month').format('YYYY-MM'),
  customerId: '',
});

//限制查询日期，开始日期不能大于结束日期
function disabledStartDate(beginDate) {
  const endDate = queryParam.endDate;
  if (!beginDate || !endDate) {
    return false;
  }
  return beginDate.valueOf() > moment(endDate).valueOf()
}

function disabledEndDate(endDate) {
  const beginDate = queryParam.beginDate;
  if (!endDate || !beginDate) {
    return false;
  }
  return moment(beginDate).valueOf() > endDate.valueOf();
}

//资方产品------------------------------
const cascader = reactive<any>({
  ids: [],
  options: [],
});

function customerCascader(value) {
  if (value && value.length > 0) {
    queryParam.customerId = value.join(",");
  } else {
    queryParam.customerId = "";
  }
}

const filter = (inputValue: string, path) => {
  return path.some((option) => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
};

//初始化------------列表组件--------------------- 
const columns: BasicColumn[] = [
  {dataIndex:'capitalName',title:'月份/资方/产品',width:160,align:'left', 
    customRender: ({ text, record }) => {
      const color = record.hasChildren == 'true' || record.type == '4' || text == '合计' ? '' : 'green';
      return render.renderColor(text, color);
    },
  },
  {dataIndex:'amountTotal',title:'放款金额',width:90,align:'right',className:"text-red-600"},
  {dataIndex:'amountTotalPer',title:'融资占比',width:60,align:'right',className:"text-red-600"},
  {dataIndex:'orderCount',title:'放款台次',width:55,className:"text-blue-600"},
  {dataIndex:'orderCountPer',title:'台次占比',width:55,align:'right',className:"text-blue-600"},
  {dataIndex:'Amount_00_06',title:'6万以内',width:55,className:"text-green-600"},
  {dataIndex:'Amount_06_10',title:'6-10万',width:55,className:"text-green-600"},
  {dataIndex:'Amount_10_15',title:'10-15万',width:55,className:"text-green-600"},
  {dataIndex:'Amount_15_20',title:'15万以上',width:55,className:"text-green-600"},
  {dataIndex:'dealerRebate',title:'车商返利',width:80,align:'right'},
  {dataIndex:'qyPercentage',title:'区域提成',width:80,align:'right'},
  {dataIndex:'zfProfitGross',title:'区域毛利',width:80,align:'right'},
  {dataIndex:'nbProfitGross',title:'股东毛利',width:80,align:'right',auth:'order:shareholder',}
];

// 列表页面公共参数、方法
const loading = ref<boolean>(false);
const dataSource  = ref<any[]>([]);
const summaryData = ref<any[]>([]);
const { prefixCls, tableContext } = useListPage({
  tableProps: {
    rowKey: "id",
    size: "small",
    dataSource: dataSource,
    columns: columns,
    pagination: false,
    isTreeTable: true,
    striped: true,
    useSearchForm: false,
    bordered: true,
    showTableSetting: false,
    showActionColumn: false,
    resizeHeightOffset: 40,
    showSummary: true,
    summaryData: summaryData,
    onExpand: onExpand
  }
});

//-----------------------------列表事件-------------------------------------
//加载table数据方法
const [registerTable, { reload, collapseAll }] = tableContext;
const url = "/report/orders";
async function loadData(params) {
  loading.value = true;
  let result = await defHttp.get({ url, params });
  loading.value = false;
  return result;
}

/** 点击展开图标时触发 */
async function onExpand(isExpand, rowData) {
  if (isExpand && rowData.hasChildren === "true" && rowData.children.length === 0) {
    let params = {...queryParam, parent_id: rowData.id, type: rowData.type }
    const res = await loadData(filterObj(params));
    rowData.children = res.rows;
  }
}

// 取后台数据
async function loadRootData() {
  const res = await loadData(filterObj(queryParam));
  if (res) {
    dataSource.value = res.rows;
    summaryData.value = res.footer;
  } else {
    dataSource.value = [];
    summaryData.value = [];
  }
}

// 查询按钮
function searchQuery() {
  //reload();
  nextTick(collapseAll);
  loadRootData();
}

//收款统计 - 导出
const { handleImportXls, handleExportXls } = useMethods();
function onExportXls() {
  handleExportXls('收款统计', businessCustomerExportUrl, filterObj(queryParam));
}

//单击行
let selectRows = reactive<any>({id: ''});
function handleClick(record) {
  // if (selectRows.id == record.id) {
  //   selectRows.id = ''
  // } else {
    
  // }
  selectRows.id = record.id
}

//双击行
function handleDblclick(record) {
  if (!selectRows.id) {
    return
  }
  if (record.type != '2') {
    return
  }
  var params = {
    id: record.id,
    beginDate : queryParam.beginDate,
    endDate: queryParam.endDate,
    cIds: [ record.id ],
    ...record
  }
  //console.info(record)
  handleDetail(params);
}

function rowClassName(record) {
  return record.id === selectRows.id ? 'row-selected' : '';
}
//-----------------------------列表事件-------------------------------------


//-----------------------------弹出详情页面-------------------------------------
//注册model-----------------------------------------
const [registerDetail, { openModal : openDetail }] = useModal();

/**
 * 详情
 */
async function handleDetail(record: Recordable) {
  if (!selectRows.id) {
    return
  }
  Object.assign(record, selectRows)
  openDetail(true, {
    record,
    isUpdate: true,
    showFooter: true,
  });
}
//-----------------------------弹出详情页面-------------------------------------

onMounted(async () => {
  await nextTick();
  let res = await customerSelect();
  Object.assign(cascader.options, res);

  //默认执行查询
  searchQuery();
});

</script>
<style scoped>
.ant-row1 > div:not(.gutter-row):nth-child(2n + 1) {
  background: rgba(0, 146, 255, .75);
}

.ant-row1 > div:not(.gutter-row) {
  padding: 16px 0;
  background: #0092ff;
}

.ant-col1 {
  position: relative;
  max-width: 100%;
  min-height: 1px;
}

/** 2022-05-30 */
.jeecg-basic-table-form-container .ant-form {
  margin: 0px;
}

.jeecg-basic-table .ant-form-item {
  margin-bottom: 5px;
}

::v-deep(.ant-table-tbody .clickRowStyl) {
  border-color: #76B4AC!important;
  background: #eee!important;
  color: #007465!important;
}

.datagrid-row-selected {
  border-color: #76B4AC;
  background: #eee;
  color: #007465;
}

.datagrid-row-over{
  background: #F5F5F5;
  color: #444;
  cursor: default;
  font-weight: normal;
}
</style>
